package com.ls.day2;

import org.omg.CosNaming.BindingIterator;

public class Solution {

    public static void main(String[] args) {
        ListNode l1 = null,l2 = null;
        int a[] = {1,8};
        int b[] = {0};
        l1=init(a,2);
        l2=init(b,1);
        show(l1);
        show(l2);
        ListNode s = addTwoNumbers(l1,l2);
        show(s);
    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head,link = null,fro;
        fro = head = link;
        int a=0,b=0,val1,val2;
        while (l1!=null&&l2!=null||b!=0){
            if (l1!=null)
                val1=l1.val;
            else val1=0;
            if(l2!=null)
                val2=l2.val;
            else val2=0;

            a = (val1 + val2 + b)%10;
            b = (val1 + val2 + b)/10;

            if(link == null){
                link = new ListNode(a);
                head = fro = link;
            }else{
                link = new ListNode(a);
                fro.next = link;
                fro = link;
            }


            if (l1!=null)
                l1 = l1.next;
            if(l2!=null)
                l2 = l2.next;

        }

        if(l1!=null){
            fro.next=l1;
        }
        if(l2!=null){
            fro.next=l2;
        }

        return head;
    }

    public static ListNode init(int a[], int n){
        ListNode p,q;
        p = new ListNode(a[0]);
        q=p;
        for (int i=1;i<n;i++){
            q.next = new ListNode(a[i]);
            q = q.next;
        }
        return p;
    }

    public static void show(ListNode l){
        while (l!=null){
            System.out.print(l.val);
            l=l.next;
        }
        System.out.println("");
    }
}
